package com.mars.service;

import com.google.common.base.Preconditions;
import com.mars.common.RequestHolder;
import com.mars.dao.SysAclMapper;
import com.mars.dao.SysAclModuleMapper;
import com.mars.exception.ParamException;
import com.mars.param.AclModuleParam;
import com.mars.pojo.SysAclModule;
import com.mars.util.BeanValidator;
import com.mars.util.IpUtil;
import com.mars.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author MARS
 * @date 2018/1/17
 */

@Service
public class SysAclModuleService {

    @Resource
    private SysAclModuleMapper sysAclModuleMapper;
    @Resource
    private SysAclMapper sysAclMapper;
    @Resource
    private SysLogService sysLogService;

    public void save(AclModuleParam param){
        // 参数校验
        BeanValidator.check(param);
        if (checkExist(param.getParentId(),param.getName(),param.getId())) {
            throw new ParamException("同一层级下存在相同的权限模块名称");
        }

        SysAclModule aclModule = SysAclModule.builder().name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        aclModule.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()), param.getParentId()));
        aclModule.setOperator(RequestHolder.getCurrentUser().getUsername());
        aclModule.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        aclModule.setOperateTime(new Date());
        sysAclModuleMapper.insertSelective(aclModule);
        sysLogService.saveAclModuleLog(null,aclModule);
    }

    public void update(AclModuleParam param){
// 参数校验
        BeanValidator.check(param);
        if (checkExist(param.getParentId(),param.getName(),param.getId())) {
            throw new ParamException("同一层级下存在相同的权限模块名称");
        }

        // 检查id对应的实体类是否存在
        SysAclModule before = sysAclModuleMapper.selectByPrimaryKey(param.getId());
        // 检查实体类是否存在
        Preconditions.checkNotNull(before,"待更新的权限模块不存在");

        SysAclModule after = SysAclModule.builder().id(param.getId()).name(param.getName()).parentId(param.getParentId()).seq(param.getSeq())
                .status(param.getStatus()).remark(param.getRemark()).build();
        after.setLevel(LevelUtil.calculateLevel(getLevel(param.getParentId()),param.getParentId()));
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());

        updateWithChild(before,after);
        sysLogService.saveAclModuleLog(before,after);
    }

    @Transactional(rollbackFor = Exception.class)
    private void updateWithChild(SysAclModule before,SysAclModule after) {
        // 是否更新子部门
        String newLevelPrefix = after.getLevel();
        String oldLevelPrefix = before.getLevel();
        // 如果两个level不一致，需要做子部门的更新
        if ( !after.getLevel().equals(before.getLevel())) {
            List<SysAclModule> aclModuleList = sysAclModuleMapper.getChildAclModuleListByLevel(before.getLevel());
            if (CollectionUtils.isNotEmpty(aclModuleList)) {
                for (SysAclModule aclModule : aclModuleList){
                    String level = aclModule.getLevel();
                    if(level.indexOf(oldLevelPrefix) == 0 ) {
                        level = newLevelPrefix + level.substring(oldLevelPrefix.length());
                        aclModule.setLevel(level);
                    }
                }
                //批量更新level
                sysAclModuleMapper.batchUpdateLevel(aclModuleList);
            }
        }
        sysAclModuleMapper.updateByPrimaryKey(after);
    }

    private boolean checkExist(Integer parentId,String aclModuleName,Integer deptId){
        return sysAclModuleMapper.countByNameAndParentId(parentId,aclModuleName,deptId) > 0 ;
    }

    private String getLevel(Integer aclModuleId){
        SysAclModule sysAclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        if (sysAclModule == null) {
            return null;
        }
        return sysAclModule.getLevel();
    }

    public void delete(int aclModuleId) {
        // 先判断当前module是否存在
        SysAclModule aclModule = sysAclModuleMapper.selectByPrimaryKey(aclModuleId);
        // 校验对象是否存在
        Preconditions.checkNotNull(aclModule,"待删除的权限模块不存在，不能删除");
        // 判断是否存在子模块
        if (sysAclModuleMapper.countByParentId(aclModule.getId()) > 0) {
            throw new ParamException("该模块下存在子模块，不能删除");
        }
        // 判断子部门下存在权限点
        if ( sysAclMapper.countByAclModuleId(aclModule.getId()) > 0 ) {
            throw new ParamException("该模块下存在权限点，不能删除");
        }

        sysAclModuleMapper.deleteByPrimaryKey(aclModuleId);
    }
}
